package com.ctc.lottery.filter;

import com.alibaba.fastjson.JSON;
import com.ctc.lottery.common.BaseContext;
import com.ctc.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 检查用户是否已完成登录
 */
@Slf4j
@WebFilter(filterName = "/loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Autowired
    private StringRedisTemplate redisTemplate;

    // 路径匹配器：进行路径比较，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",request.getRequestURI());
        // 2、判断本次请求是否需要处理
        // 定义不需要处理的请求路径
        String[] urls = new String[]{
                "/admin/login",
                "/menber/login",
                "/menber/addMenber",
                "/swagger-ui.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v2/**",
                "/favicon.ico"
        };
        boolean check = check(urls, requestURI);

        // 3、如果不需要处理，直接放行
        if (check){
            log.info("本次请求{}不需要处理",request.getRequestURI());
            filterChain.doFilter(request,response);
            return;
        }

        // 4、判断是否登录
        String token = request.getHeader("token");
        if (token != null) {
            String userName = redisTemplate.opsForValue().get(token);
            if (userName != null) {
                log.info("当前登录用户为：{}", userName);
                redisTemplate.expire(token, 300, TimeUnit.MINUTES);
                BaseContext.setCurrentUserName(userName);
                filterChain.doFilter(request, response);
                return;
            }
        }


        // 5、如果没有登录，返回未登录结果，通过输出流的方式向客户端页面相应数据
        log.info("用户未登录");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(R.error(HttpStatus.SC_UNAUTHORIZED,"登录信息已过期，请重新登录").put("data","NOTLOGIN")));

    }

    /**
     * 进行路径匹配：检测当前路径是否需要放行
     * @param urls  放行的路径
     * @param requestURI  需要检测的url
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }

}
